package com.jushu.storbox.adapter;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.jushu.storbox.R;
import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.actions.ThumbnailAction;
import com.jushu.storbox.callback.ShareNodeTypeSort;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.constant.MessageCode;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.entities.FileType;
import com.jushu.storbox.handler.ClientExceptionRelateHandler;
import com.jushu.storbox.operation.group.MySendShareOperation;
import com.jushu.storbox.util.DirectoryUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.view.dialog.PopupMenuWindow;
import com.huawei.sharedrive.sdk.android.modelV2.response.INodeShareV2;

public class MySendShareDisplayAdapter extends ListDisplayResolveAdapter<INodeShareV2, MySendShareOperation<INodeShareV2>> {

	Context context;
	LayoutInflater inflater;

	public MySendShareDisplayAdapter(Context context, List<INodeShareV2> datasList) {
		super(datasList);
		this.context = context;
		inflater = LayoutInflater.from(context);
	}

	public View getView(int position, View contentView, ViewGroup parent) {
		ViewHolder holder = null;
		if (contentView == null) {
			holder = new ViewHolder();
			contentView = holder.inflateFromXML(parent);
			contentView.setTag(holder);
		} else {
			holder = (ViewHolder) contentView.getTag();
		}
		holder.updataViewFromData(position, getItem(position));
		return holder.getHolderView();
	}

	public class ViewHolder implements IViewHolder<INodeShareV2> {

		View contentView;
		ImageView mItemIcon;
		TextView mItemName;
		TextView mItemExtendInfo;
		TextView mItemSize;
		View moreOperation;
		// menu related
		PopupMenuWindow popWindow;
		View viewShare;
		View cancelShare;

		// relate to adapter
		int mIndex;
		INodeShareV2 mData;
		String iconPath;

		public View inflateFromXML(ViewGroup parent) {
			contentView = inflater.inflate(R.layout.item_share_byme_filelist, parent, false);
			mItemIcon = (ImageView) contentView.findViewById(R.id.item_type_img);
			mItemName = (TextView) contentView.findViewById(R.id.item_name_text);
			mItemExtendInfo = (TextView) contentView.findViewById(R.id.item_date_text);
			mItemSize = (TextView) contentView.findViewById(R.id.item_filelist_file_size);
			moreOperation = contentView.findViewById(R.id.item_more_ll);
			//
			popWindow = new PopupMenuWindow(context, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, R.layout.action_myshare_popup_window) {
				@Override
				protected void onInflaterFinished(View contentView) {
					viewShare = contentView.findViewById(R.id.adapter_view_myshareitem_window_more_viewshare);
					cancelShare = contentView.findViewById(R.id.adapter_view_myshareitem_window_more_cancelshare);
					super.onInflaterFinished(contentView);
				}
			};
			return contentView;
		}

		public void updataViewFromData(int index, INodeShareV2 data) {
			mData = data;
			// binding data to view
			mItemIcon.setImageResource(getTypeImgeID(data.getType(), data.getName()));
			mItemName.setText(data.getName());
			if (data.getType() == FileType.File.value()) {

				mItemExtendInfo.setVisibility(View.VISIBLE);

				if (null == data.getModifiedAt()) {
					mItemExtendInfo.setText("");
				} else {
					mItemExtendInfo.setText(PublicTools.longToString(data.getModifiedAt()));
				}

				mItemSize.setVisibility(View.VISIBLE);
				mItemSize.setText(PublicTools.changeBKM(String.valueOf(data.getSize())));

			} else {
				mItemExtendInfo.setVisibility(View.INVISIBLE);
				mItemSize.setVisibility(View.INVISIBLE);
			}

			// init listener
			moreOperation.setOnClickListener(new OnClickListener() {
				public void onClick(View view) {
					int[] loction = new int[2];
					view.getLocationOnScreen(loction);
					int showMoreMenuY = loction[1];
					popWindow.showAtLocation(contentView, Gravity.TOP, 0, showMoreMenuY + (view.getHeight() / 2 + 20));
				}
			});
			viewShare.setOnClickListener(new OnClickListener() {
				public void onClick(View arg0) {
					if (popWindow != null && popWindow.isShowing()) {
						popWindow.dismiss();
					}
					if (getOperation() != null) {
						getOperation().onViewShareItem(mIndex, mData);
					} else {
						LogUtil.e(TAG, "current operation is null");
					}
				}
			});
			cancelShare.setOnClickListener(new OnClickListener() {
				public void onClick(View arg0) {
					if (popWindow != null && popWindow.isShowing()) {
						popWindow.dismiss();
					}
					if (getOperation() != null) {
						getOperation().onCancelShareItem(mIndex, mData);
					} else {
						LogUtil.e(TAG, "current operation is null");
					}
				}
			});
		}

		private int getTypeImgeID(int type, String itemName) {
			int typeImgResId = R.mipmap.default_file_icon;
			if (type == FileType.File.value()) {
				if (PublicTools.isFileType(itemName, Constant.WORD_TYPE)) {
					typeImgResId = R.mipmap.doc;
				} else if (PublicTools.isFileType(itemName, Constant.PPT_TYPE)) {
					typeImgResId = R.mipmap.ppt;
				} else if (PublicTools.isFileType(itemName, Constant.IMAGE_TYPE)) {
					typeImgResId = R.mipmap.empty_pic;
					loadRealThumbnail();
				} else if (PublicTools.isFileType(itemName, Constant.RAR_TYPE)) {
					typeImgResId = R.mipmap.rar;
				} else if (PublicTools.isFileType(itemName, Constant.ZIP_TYPE)) {
					typeImgResId = R.mipmap.rar;
				} else if (PublicTools.isFileType(itemName, Constant.VIDEO_TYPE)) {
					typeImgResId = R.mipmap.video;
				} else if (PublicTools.isFileType(itemName, Constant.MUSIC_TYPE)) {
					typeImgResId = R.mipmap.music;
				} else if (PublicTools.isFileType(itemName, Constant.TXT_TYPE)) {
					typeImgResId = R.mipmap.txt;
				} else if (PublicTools.isFileType(itemName, Constant.PDF_TYPE)) {
					typeImgResId = R.mipmap.pdf;
				} else if (PublicTools.isFileType(itemName, Constant.EXCEL_TYPE)) {
					typeImgResId = R.mipmap.excel;
				} else {
					typeImgResId = R.mipmap.default_file_icon;
				}
			} else {
				typeImgResId = R.mipmap.folder_im;
			}
			return typeImgResId;
		}

		private void loadRealThumbnail() {
			try {
				iconPath = DirectoryUtil.genThumbnailFileFullName(context, mData.getOwnerId().toString(), mData.getNodeId().toString(), mData.getName());
				File thumBnail2 = new File(iconPath);
				if (!thumBnail2.exists()) {
					new ThumbnailAction().downloadThumbnailIcon(context, mData.getOwnerId().toString(), mData.getNodeId().toString(), iconPath, handler);
				} else {
					Message msg_download = new Message();
					msg_download.what = MessageCode.REQUEST_THUMBNAIL_INLOCAL;
					handler.sendMessage(msg_download);
				}
			} catch (Exception e) {
				LogUtil.e(TAG, "fileType is image that show fail..." + e.getLocalizedMessage());
			}
		}

		@Override
		public View getHolderView() {
			return contentView;
		}

		@Override
		public INodeShareV2 getHolderDate() {
			return mData;
		}

		ClientExceptionRelateHandler handler = new ClientExceptionRelateHandler() {

			@Override
			public Context getContext() {
				return context;
			}

			public void handleMessage(final Message msg) {
				switch (msg.what) {
				case MessageCode.REQUEST_THUMBNAIL_INLOCAL:
					new Thread(new Runnable() {
						public void run() {
							LogUtil.i(TAG, "thumb path: " + iconPath);
							Bitmap bmp = BitmapFactory.decodeFile(iconPath);
							ShareDriveApplication.getInstance().addCloudBitmaps(bmp);
							Message message = new Message();
							message.what = UiConstant.UPDATE_TYPE_ICON;
							message.obj = bmp;
							handler.sendMessage(message);
						}
					}).start();
					break;

				case UiConstant.UPDATE_TYPE_ICON:// refresh image ui
					Bitmap bmp = (Bitmap) msg.obj;
					if (null != bmp) {
						mItemIcon.setImageBitmap(bmp);
					} else {
						LogUtil.e(TAG, "bitmap is null, show default img...");
					}
					break;

				default:
					super.handleMessage(msg);
				}
			}
		};

		@SuppressLint("SimpleDateFormat")
		private String formatDate(long lData) {
			SimpleDateFormat timeDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
			return timeDateFormat.format(lData);
		}

		@Override
		public void updataHolderView() {
			// binding data to view
			// mItemIcon.setImageResource(getTypeImgeID(data.getType(),""));
			mItemName.setText(mData.getName());
			if (mData.getType() == FileType.File.value()) {
				mItemExtendInfo.setVisibility(View.VISIBLE);

				if (null == mData.getModifiedAt()) {
					mItemExtendInfo.setText("");
				} else {
					mItemExtendInfo.setText(PublicTools.longToString(mData.getModifiedAt()));
				}

				mItemSize.setVisibility(View.VISIBLE);
				mItemSize.setText(PublicTools.changeBKM(String.valueOf(mData.getSize())));

			} else {
				mItemExtendInfo.setVisibility(View.INVISIBLE);
				mItemSize.setVisibility(View.INVISIBLE);
			}
		}
	}

	@Override
	protected Comparator<INodeShareV2> getDefaultComparator() {
		SharedPreferences preference = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
		Editor edit = preference.edit();
		int shareSendSortCurrent = preference.getInt(UiConstant.SHARE_SEND_CURRENT_SORT, UiConstant.SHARE_SEND_SORT_BY_FILENAME);
		edit.putInt(UiConstant.SHARE_SEND_CURRENT_SORT, shareSendSortCurrent);
		edit.commit();
		return (new ShareNodeTypeSort(shareSendSortCurrent));
	}

}
